package com.sunrise.controller;

import com.google.gson.Gson;
import com.sunrise.base.BaseInfoProperties;
import com.sunrise.pojo.system.Group;
import com.sunrise.service.GroupService;
import com.sunrise.util.GsonUtils;
import com.sunrise.vo.system.group.GroupPageVO;
import com.sunrise.vo.system.group.GroupVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import result.GraceJSONResult;
import result.PageGridResult;
import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: liansen
 * @Date: 2023-08-27  21:22
 */
@RestController
@RequestMapping("/system/group")
public class GroupController extends BaseInfoProperties {
    @Resource
    private GroupService groupService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/saveOrUpdate")
    public GraceJSONResult saveOrUpdate(@RequestBody GroupVO groupVO){
        Group group = new Group();
        BeanUtils.copyProperties(groupVO, group);
        if(StringUtils.isBlank(groupVO.getId())){
            //新增
            groupService.saveOrUpdate(group);
        }else {
            //更新
            groupService.updateById(group);
        }
        return GraceJSONResult.ok();
    }

    //通过id查询用户组
    @GetMapping("/getById")
    public GraceJSONResult getById(@RequestParam String id){
        Group group = groupService.getById(id);
        return GraceJSONResult.ok(group);
    }

    @DeleteMapping("/delete")
    public GraceJSONResult delete(@RequestParam("id") String id){
        //TODO
        groupService.getBaseMapper().deleteById(id); //不报错
        //groupService.removeById(id); //报错?????

        return GraceJSONResult.ok();
    }

    //多条件分页查询
    @PostMapping("/queryPage")
    public GraceJSONResult queryPage(@RequestBody GroupPageVO pageVO){
        PageGridResult result = groupService.pageQuery(pageVO);
        return GraceJSONResult.ok(result);
    }

    //测试mysql与redis数据一致性
    @GetMapping("/getAll")
    public GraceJSONResult getAll(){
        String groupList = redisTemplate.opsForValue().get(GROUP_LIST);
        List<Group> groups;
        if(StringUtils.isNotBlank(groupList)){
            groups = GsonUtils.stringToListAnother(groupList, Group.class);
        }else {
            groups = groupService.getBaseMapper().selectList(null);
            String groupStr = new Gson().toJson(groups);
            redisTemplate.opsForValue().set(GROUP_LIST, groupStr);
        }
        return GraceJSONResult.ok(groups);
    }
}
